﻿using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace _批量插入上万条数据
{
    public static class SqlUtil
    {
        public static readonly string ConnString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;

        public static void InsertMassData(string strConn, DataTable dt, string tableName)
        {
            using (SqlBulkCopy sbc = new SqlBulkCopy(ConnString, SqlBulkCopyOptions.UseInternalTransaction))
            {
                sbc.BatchSize = dt.Rows.Count;
                sbc.BulkCopyTimeout = 1800;
                sbc.DestinationTableName = tableName;
                foreach (DataColumn column in dt.Columns)
                {
                    sbc.ColumnMappings.Add(column.ColumnName, column.ColumnName);
                }

                sbc.WriteToServer(dt);
            }

        }

        public static int ExecutionSql(string connString, string strSql, CommandType type, params SqlParameter[] param)
        {
            using (SqlConnection conn = new SqlConnection(connString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = strSql;
                    cmd.CommandType = type;
                    cmd.Parameters.AddRange(param);
                    return cmd.ExecuteNonQuery();
                }
            }
        }
    }
}
